<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { userGetMenu, userSetMenu, menuList } from '../../../api'
import {Plus} from '@element-plus/icons-vue'
import {useRoute} from 'vue-router'
const route = useRoute()




// 分页数据对象
const paginationData = reactive({
    pageNum: 1,
    pageSize: 10
});
// 请求列表数据
const getListData = () => {
    menuList(paginationData).then(({ data }) => {
        console.log(data)
        const { list, total } = data.data
        tableData.list = list;
        tableData.total = total

    })
}

// 权限树形结构数据
const permissionData = ref([]);
// 获取权限树形结构数据 并赋值给 permissionData
onMounted(() => {
    userGetMenu().then(({ data }) => {
        permissionData.value = data.data
    })
    getListData()
})
// 列表数据
const tableData = reactive({
    list: [],
    total: 0
})
// 分页事件 
const handleSizeChange = (val) => {
    paginationData.pageSize = val
    getListData()
}
// 分页改变事件
const handleCurrentChange = (val) => {
    paginationData.pageNum = val
    getListData()
}
// 弹窗的显示隐藏状态
const dialogVisible = ref(false)
// 关闭弹窗的回调函数
const beforeClose = () => {
    // 关闭 Dialog 前执行的操作
    dialogVisible.value = false
    // 重置表单
    formRef.value.resetFields()
    //tree选择重置
    treeRef.value.setCheckedKeys(defaultKeys)

}
// form 数据
const form = reactive({
    id: '',
    name: '',
    permissions: ''
})

// 选中权限
const defaultKeys = [4, 5]
//  ref 实例 实例 
const treeRef = ref()
//  表单提交
const formRef = ref()
// 确认按钮
const confirm = async (formEl) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (!valid) {
            console.log('error submit!', fields)
        } else {
            // 拿到选中的权限
            const permissions = JSON.stringify(treeRef.value.getCheckedKeys())
            userSetMenu({
                name: form.name,
                permissions: permissions,
                id: form.id
            }).then(({ data }) => {
                console.log(data)

                if (data.code === 10000) {
                    ElMessage.success('添加成功')
                    beforeClose()
                    getListData()
                }

            })
        }


    })
}
// 表单验证
const rules = reactive({
    name: [
        { required: true, message: '请输入权限名称', trigger: 'blur' },
        { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
    ],
});
// 打开对话框
const open = (rowData = {}) => {
    dialogVisible.value = true
    // 弹窗打开form生成是异步的
    nextTick(() => {
        if (rowData) {
            Object.assign(form, { id: rowData.id, name: rowData.name })
            treeRef.value.setCheckedKeys(rowData.permission)
        }
    })

}
</script>

<template>
    <panel-head  :route="route"/>
    <div class="btns">
        <!-- 打开对话框 -->
        <el-button :icon="Plus" type="primary"  size="small" @click="open(null)">新增</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData.list">
        <el-table-column prop="id" label="id" width="width" />
        <el-table-column prop="name" label="权限名称" width="width" />
        <el-table-column prop="permissionName" label="权限" width="width" />
        <el-table-column label="操作">
            <template #default="scope">
                <el-button type="primary" @click="open(scope.row)">编辑</el-button>
                <el-button type="danger">删除</el-button>
            </template>
        </el-table-column>

    </el-table>
    <!-- 分页 -->
    <div class="pagination-info">
        <el-pagination v-model:current-page="paginationData.pageNum" size="small" :page-size="paginationData.total"
            :background="false" layout="->,total, prev, pager, next" :total="tableData.total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <!-- 对话框 -->
    <el-dialog v-model="dialogVisible" :before-close="beforeClose" title="添加权限" width="500" draggable>
        <el-form ref="formRef" :model="form" label-width="100px" label-position :rules="rules">
            <el-form-item v-show="false" prop="id">
                <el-input v-model="form.id"></el-input>
            </el-form-item>
            <el-form-item label="权限名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入权限名称"></el-input>
            </el-form-item>
            <el-form-item label="权限" prop="permissions">
                <el-tree ref="treeRef" style="max-width: 600px;" :data="permissionData" node-key="id" show-checkbox
                    :default-checked-keys="defaultKeys" :default-expanded-keys="[2]">
                </el-tree>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="confirm(formRef)">确认</el-button>
            </div>
        </template>
    </el-dialog>

</template>

<style lang="less" scoped>
.btns {
    padding: 10px 0 10px 10px;
    background-color: #fff;
}
</style>